package main

import (
	"encoding/json"
	"log"
	"mygoedu/day11/socket"
	"net"
	"strconv"
	"sync"
	"time"
)

func main() {
	ip := "127.0.0.1"
	port := 8080
	_, err := net.ResolveUDPAddr("udp", ip+":"+strconv.Itoa(port))
	socket.CheckError(err)

	conn, err := net.DialTimeout("udp", ip+":"+strconv.Itoa(port), 2*time.Second)
	socket.CheckError(err)

	request := socket.Request{
		A: 3,
		B: 9,
	}
	requestBytes, _ := json.Marshal(request)

	const p = 10
	wg := sync.WaitGroup{}
	wg.Add(10)
	for i := 0; i < p; i++ {
		go func() {
			defer wg.Done()
			for {
				_, err := conn.Write(requestBytes)
				socket.CheckError(err)
				log.Println("write request", string(requestBytes))

				responseBytes := make([]byte, 256)
				readLen, err := conn.Read(responseBytes)
				socket.CheckError(err)

				var response socket.Response
				json.Unmarshal(responseBytes[0:readLen], &response)
				log.Println("receive response", response.Sum)
				time.Sleep(1 * time.Second)
			}
		}()

	}
	wg.Wait()
}
